<template>
    <div class="login-log-container">
        <!-- 表单搜索项 -->
        <el-form :model="params">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="领料单编号">
                        <el-input v-model="params.pickingId" placeholder="请输入领料单编号" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="领料单名称">
                        <el-input v-model="params.pickingName" placeholder="请输入领料单名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="领料日期">
                        <el-date-picker v-model="params.pickingDate" type="date" placeholder="领料日期"
                            style="width: 100%;"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="状态">
                        <el-input v-model="params.status" placeholder="请输入状态" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                    <el-button type="primary" plain :icon="Refresh" @click="handleReset">重置</el-button>
                </el-col>
            </el-row>
        </el-form>

        <!-- 按钮组 -->
        <el-row class="button-group">
            <el-col :span="10">
                <el-button type="primary" :icon="Plus" plain @click="openInsert">新增</el-button>
                <el-button type="danger" plain :disabled="deleteDisabled" :icon="Delete"
                    @click="handleDelete">删除</el-button>
                <el-button type="danger" plain @click="clearAll">清空</el-button>
            </el-col>
            <el-col :span="14">
                <div class="button-right">
                    <el-tooltip content="隐藏搜索" placement="top">
                        <el-button :icon="Search" circle @click="toggleSearchVisibility"></el-button>
                    </el-tooltip>
                    <el-tooltip content="刷新" placement="top">
                        <el-button :icon="Refresh" circle @click="handleReset"></el-button>
                    </el-tooltip>
                </div>
            </el-col>
        </el-row>

        <!-- 数据表格 -->
        <el-row>
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="40"></el-table-column>
                <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
                <el-table-column prop="pickingId" label="领料单编号" align="center"></el-table-column>
                <el-table-column prop="pickingName" label="领料单名称" align="center"></el-table-column>
                <el-table-column prop="pickingDate" label="领料日期" align="center"></el-table-column>
                <el-table-column prop="status" label="状态" align="center">
                    <template #default="scope">
                        <span>{{ scope.row.status == 0 ? '草稿' : scope.row.status == 1 ? '已完成' : '未知状态' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="250px">
                    <template #default="scope">
                        <el-button :row="scope.row" type="primary" @click="openUpdate(scope.row)" text size="small"
                            :icon="EditPen">修改</el-button>

                        <el-button type="success" text size="small" :icon="Check"
                            @click="handleExecutePicking(scope.row)">执行领料</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>

        <!-- 分页组件 -->
        <el-row>
            <el-col :span="24">
                <div class="demo-pagination-block">
                    <el-pagination :current-page="params.currentPage" :page-size="params.pageSize" background
                        :page-sizes="pageSizes" layout="total,sizes,prev,pager,next,jumper" :total="pageResult.total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>

        <!-- 添加编辑对话框 -->
        <el-dialog v-model="dialogFormVisible" :title="title" width="700" @close="closeDialog">
            <el-form :model="form">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="领料单编号">
                            <el-input v-model="form.pickingId" :disabled="!isNew" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="领料单名称">
                            <el-input v-model="form.pickingName" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="领料日期">
                            <el-date-picker v-model="form.pickingDate" type="date" placeholder="领料日期"
                                style="width: 100%;"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="选择仓库">
                            <el-cascader v-model="form.warehouseNames" ref="cascader" :options="options"
                                @change="handleChange" placeholder="请选择仓库" clearable></el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="单据状态">
                            <el-select v-model="form.status" placeholder="请选择状态">
                                <el-option label="草稿" value="0"></el-option>
                            </el-select>
                        </el-form-item>

                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="生产工单">
                            <el-input v-model="form.codeChangeNumber" placeholder="请输入工单编码">
                                <template #append>
                                    <el-button :icon="Search" @click="ShengchangSearch"></el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="id">
                            <el-input v-model="form.productionCode">
                            </el-input>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="form.remark"
                                :autosize="{ minRows: 4, maxRows: 8 }"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <!-- 物料信息 -->
            <div v-if="isEditing">
                <el-divider>
                    <span>物料信息</span>
                </el-divider>
                <el-tabs type="border-card">
                    <el-button type="primary" :icon="Plus" plain @click="openAddMaterialDialog">新增</el-button>
                    <el-button type="danger" plain :disabled="deletesales" :icon="Delete"
                        @click="handleDelete">删除</el-button>
                </el-tabs>

                <div>
                    <el-row>
                        <el-table ref="xiaoshoudindanTable" :data="materialResult" style="width: 100%;"
                            @selection-change="handleSelectionChangeWuliao">
                            <el-table-column type="selection" :selectable="selectable" width="40"></el-table-column>
                            <el-table-column prop="materialProductCode" label="产品物料编码" width="120"></el-table-column>
                            <el-table-column prop="productName" label="产品物料名称" width="120"></el-table-column>
                            <el-table-column prop="specificationAndModel" label="规格型号" width="120"></el-table-column>
                            <el-table-column prop="quantityIssued" label="领料数量" width="120"></el-table-column>
                            <el-table-column prop="unitOfMeasure" label="单位" width="120"></el-table-column>
                            <el-table-column prop="inboundBatchNumber" label="入库批次号" width="120"></el-table-column>
                            <el-table-column prop="warehouseName" label="仓库" width="120"></el-table-column>
                            <el-table-column prop="locationName" label="库区" width="120"></el-table-column>
                            <el-table-column prop="areaName" label="库位" width="120"></el-table-column>
                        </el-table>
                    </el-row>
                </div>
            </div>

            <span>
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="isNew ? confirmAdd() : confirmUpdate()">
                    确认
                </el-button>
            </span>
        </el-dialog>

        <!-- 新增物料对话框 -->
        <el-dialog v-model="addMaterialDialogVisible" title="新增物料" @close="closeAddMaterialDialog" width="800px">
            <el-form :model="addMaterialForm" ref="formRef">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="产品物料编码">
                            <el-input v-model="addMaterialForm.materialProductCode" placeholder="产品物料编码">
                                <template #append>
                                    <el-button :icon="Search" @click="wuliaoselect"></el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="产品物料名称">
                            <el-input v-model="addMaterialForm.materialProductName" placeholder="请输入产品物料名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="领料数量">
                            <el-input type="number" v-model="addMaterialForm.quantityIssued"
                                placeholder="请输入领料数量"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="规格型号">
                            <el-input v-model="addMaterialForm.specificationAndModel" placeholder="请输入规格型号"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="单位">
                            <el-input v-model="addMaterialForm.unitOfMeasure" placeholder="请输入单位"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="批次号">
                            <el-input v-model="addMaterialForm.inboundBatchNumber" placeholder="请输入批次号"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="仓库">
                            <el-input v-model="addMaterialForm.warehouseName" placeholder="请输入仓库名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="库区">
                            <el-input v-model="addMaterialForm.warehouseAreaName" placeholder="请输入库区名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="库位">
                            <el-input v-model="addMaterialForm.warehouseLocationName" placeholder="请输入库位"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="addMaterialForm.remark" placeholder="请输入备注"
                                :autosize="{ minRows: 2, maxRows: 4 }"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeAddMaterialDialog">取 消</el-button>
                <el-button type="primary" @click="confirmAddMaterial">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 物料选择对话框 -->
        <el-dialog v-model="WarehouSeonhand" title="物料选择" @close="WarehouSeonhand = false" width="1200px">
            <div class="manage-index">
                <el-row :gutter="30">
                    <el-col :span="20">
                        <el-form :inline="true">
                            <el-form-item label="产品物料编码">
                                <el-input v-model="params.materialProductCode" placeholder="请输入产品物料编码"></el-input>
                            </el-form-item>
                            <el-form-item label="产品物料名称">
                                <el-input v-model="params.materialProductName" placeholder="请输入产品物料名称"></el-input>
                            </el-form-item>
                            <el-form-item label="入库批次号">
                                <el-input v-model="params.inboundBatchNumber" placeholder="请输入入库批次号"></el-input>
                            </el-form-item>
                        </el-form>
                        <el-form :inline="true">
                            <el-form-item label="仓库">
                                <el-input v-model="params.warehouseName" placeholder="请输入仓库"></el-input>
                            </el-form-item>
                            <el-form-item label="供应商编号">
                                <el-input v-model="params.supplierCode" placeholder="请输入供应商编号"></el-input>
                            </el-form-item>
                            <el-form-item label="供应商名称">
                                <el-input v-model="params.supplierName" placeholder="请输入供应商名称"></el-input>
                            </el-form-item>
                            <el-form-item label="库存有效期">
                                <el-date-picker v-model="params.validityPeriodOfInventory" align="right" type="date"
                                    placeholder="选择日期" :picker-options="pickerOptions"></el-date-picker>
                            </el-form-item>
                            <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
                            <el-button type="primary" plain @click="paramsReset" :icon="Refresh">重置</el-button>
                        </el-form>
                        <el-table style="width: 100%" :data="salesorder" @selection-change="handleSelectionChange2">
                            <el-table-column type="selection" :selectable="selectable" width="50"></el-table-column>
                            <el-table-column prop="materialProductCode" label="产品物料编码" width="120"></el-table-column>
                            <el-table-column prop="materialProductName" label="产品物料名称" width="120"></el-table-column>
                            <el-table-column prop="specificationAndModel" label="规格型号" width="120"></el-table-column>
                            <el-table-column prop="inventoryQuantity" label="在库数量" width="120"></el-table-column>
                            <el-table-column prop="unitName" label="单位" width="120"></el-table-column>
                            <el-table-column prop="inboundBatchNumber" label="入库批次号" width="120"></el-table-column>
                            <el-table-column prop="warehouseName" label="仓库" width="120"></el-table-column>
                            <el-table-column prop="warehouseAreaName" label="库区" width="120"></el-table-column>
                            <el-table-column prop="warehouseLocationName" label="库位" width="120"></el-table-column>
                            <el-table-column prop="supplierCode" label="供应商编号" width="120"></el-table-column>
                            <el-table-column prop="supplierName" label="供应商名称" width="120"></el-table-column>
                            <el-table-column prop="productionOrder" label="生产工单" width="120"></el-table-column>
                            <el-table-column prop="indate" label="入库日期" width="120"></el-table-column>
                            <el-table-column prop="validityPeriodOfInventory" label="库存有效期"
                                width="120"></el-table-column>
                        </el-table>
                        <!-- 分页组件 -->
                        <el-row>
                            <el-col :span="24">
                                <div class="demo-pagination-block">
                                    <el-pagination v-model:current-page="params.currentPage"
                                        v-model:page-size="params.pageSize" background
                                        :default-page-size="params.pageSize" :page-sizes="pageSizes"
                                        layout="total,sizes,prev,pager,next,jumper" :total="parseInt(pageResult.total)"
                                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                                    </el-pagination>
                                </div>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </div>
            <span>
                <el-button @click="WarehouSeonhand = false">取消</el-button>
                <el-button type="primary" @click="confirmWUliao">确认</el-button>
            </span>
        </el-dialog>

        <!-- 生产工单选择对话框 -->
        <el-dialog v-model="processTicketsDialogVisible" title="生产工单选择" @close="closeAddMaterialDialog" width="1200px">
            <div>
                <!-- 生产工单界面 -->
                <el-card style="margin-bottom:20px;">
                    <el-form :inline="true" :model="workOrderForm">
                        <el-form-item label="工单编码" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.workorderCode" placeholder="请输入工单编码" clearable />
                        </el-form-item>
                        <el-form-item label="工单名称" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.workorderName" placeholder="请输入工单名称" clearable />
                        </el-form-item>
                        <el-form-item label="来源单据" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.sourceCode" placeholder="请输入来源单据" clearable />
                        </el-form-item>
                        <el-form-item label="产品编码" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.productCode" placeholder="请输入产品编码" clearable />
                        </el-form-item>
                        <el-form-item label="产品名称" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.productName" placeholder="请输入产品名称" clearable />
                        </el-form-item>
                        <el-form-item label="客户编码" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.clientCode" placeholder="请输入客户编码" clearable />
                        </el-form-item>
                        <el-form-item label="客户名称" :class="{ 'bold-label': true }">
                            <el-input v-model="workOrderForm.clientName" placeholder="请输入客户名称" clearable />
                        </el-form-item>
                        <el-form-item label="工单类型" :class="{ 'bold-label': true }">
                            <el-select v-model="workOrderForm.workorderType" placeholder="请选择工单类型" clearable
                                @change="handleStatusChange" style="width:195px">
                                <el-option label="自产" value="SELF" />
                                <el-option label="外协" value="OUTSOURCING" />
                                <el-option label="外购" value="OUTSOURCE" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button :icon="Search" type="primary" @click="onSearch">搜索</el-button>
                            <el-button :icon="Refresh" plain @click="onReset">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>

                <el-card>

                    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChangeSCGD">
                        <el-table-column type="selection" width="40" />
                        <el-table-column label="id" prop="workorderId" width="100" />
                        <el-table-column label="工单编码" prop="workorderCode" width="200px" show-overflow-tooltip />
                        <el-table-column label="工单名称" prop="workorderName" width="100px" align="center" />
                        <el-table-column label="工单类型" width="100px" align="center">
                            <template #default="{ row }">
                                <span v-if="row.workorderType == 'SELF'">自产</span>
                                <span v-else-if="row.workorderType == 'OUTSOURCING'">外协</span>
                                <span v-else>外购</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="工单来源" width="100px" align="center">
                            <template #default="{ row }">
                                <span v-if="row.orderSource == 'ORDER'">客户订单</span>
                                <span v-else>库存备货</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="订单编号" prop="clientOrderCode" width="100px" align="center"
                            show-overflow-tooltip />
                        <el-table-column label="产品编码" prop="productCode" width="100px" align="center" />
                        <el-table-column label="产品名称" prop="productName" width="100px" align="center" />
                        <el-table-column label="规格型号" prop="productSpc" show-overflow-tooltip align="center" />
                        <el-table-column label="单位" prop="unitOfMeasure" width="100px" align="center" />
                        <el-table-column label="工单数量" prop="quantity" width="100px" align="center" />
                        <el-table-column label="调整数量" prop="quantityChanged" width="100px" align="center" />
                        <el-table-column label="已生产数量" prop="quantityProduced" width="100px" align="center" />
                        <el-table-column label="批次号" prop="batchCode" align="center" width="100px" />
                        <el-table-column label="客户编码" prop="clientCode" width="100px" align="center" />
                        <el-table-column label="客户名称" prop="clientName" show-overflow-tooltip align="center" />
                        <el-table-column label="需求日期" prop="requestDate" width="140px" align="center" />
                        <el-table-column label="单据状态" width="100px" align="center">
                            <template #default="{ row }">
                                <span v-if="row.status == 'PREPARE'">草稿</span>
                                <span v-else-if="row.status == 'CONFIRMED'">已确认</span>
                                <span v-else-if="row.status == 'APPROVING'">审批中</span>
                                <span v-else-if="row.status == 'APPROVED'">已审批</span>
                                <span v-else>已完成</span>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="pagination">
                        <el-pagination :current-page="workOrderForm.currentPage" :page-size="workOrderForm.pageSize"
                            :page-sizes="pageSizes" :total="pageResult.total"
                            layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                            @current-change="handleCurrentChange" />
                    </div>
                </el-card>
            </div>
            <span>
                <el-button @click="processTicketsDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmSC">确认</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script setup>
import { findWorkOrder } from '@/apis/lth/index';
import { findStock, findWarehousesList } from '@/apis/xms';
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
    findproductionPicking,
    deletePicking,
    updatePicking,
    insertPicking,
    insertWmIssueLine,
    findWmIssueLine,
    updatWmIssueLine,
    updatproductionPickingzt
} from '@/apis/zs/index';
import { Search, Refresh, Delete, Plus, EditPen } from '@element-plus/icons-vue';

// 响应式变量
const dialogFormVisible = ref(false);
const title = ref('新增设备类型');
const tableData = ref([]);
const pageResult = ref({});
const tablexiaoshoudindan = ref([]);

let xiaoshoudindanTable = ref(null)

//仓库列表
const options = ref([]); // 仓库列表

const processTicketsDialogVisible = ref(false); // 生产工单选择对话框

const workOrderForm = reactive({
    currentPage: 1,
    pageSize: 10,
    workorderCode: '',
    workorderName: '',
    sourceCode: '',
    productCode: '',
    productName: '',
    clientCode: '',
    clientName: '',
    workorderType: '',
});

const ShengchangSearch = () => {
    processTicketsDialogVisible.value = true; // 点击时打开对话框
    loadList(); // 加载数据
};

const loadList = async () => { // 查询工单总数据
    // 查询工单总数据
    try {
        const res = await findWorkOrder(workOrderForm);
        pageResult.value = res;
        tableData.value = pageResult.value.records; // 确保数据赋值
        console.log("Loaded tableData:", tableData.value);
    } catch (error) {
        ElMessage.error('加载工单数据失败：' + error.message);
    }
};

// 选中的工单处理逻辑
const selectedWorkOrder = ref(null); // 用于存储选中的工单数据
const handleSelectionChangeSCGD = (selection) => {
    selectedWorkOrder.value = selection.length > 0 ? selection[0] : null; // 如果选中，获取第一行
};

// 确认选中工单
const confirmSC = () => {
    if (selectedWorkOrder.value) {
        form.codeChangeNumber = selectedWorkOrder.value.workorderCode; // 更新生产工单编码
        form.productionCode = selectedWorkOrder.value.workorderId; // 存储工作单 ID
        ElMessage.success('工单信息已加载');
        processTicketsDialogVisible.value = false; // 关闭工单选择对话框
    } else {
        ElMessage.warning('请先选择一条工单');
    }

    console.log(tableData.workorderId)

};

// 物料相关逻辑
const selectedRowsWuliao = ref([]); // 用于存储选中的行

const handleSelectionChangeWuliao = (val) => {
    selectedRowsWuliao.value = val; // 更新为选中的行
};
// 处理执行领料
const handleExecutePicking = async (row) => {
    const pickingId = row.id; // 获取选择的领料单 ID
    try {
        const materialDetails = await findWmIssueLine({ id: pickingId });
        let sa = {
            lineId: pickingId,
            warehouseLocationCode: materialDetails[0].areaName,
            warehouseLocationName: materialDetails[0].locationName,
            warehouseCode: materialDetails[0].warehouseName,
            materialProductCode: materialDetails[0].materialProductCode,
            materialProductName: materialDetails[0].productName,
            specificationAndModel: materialDetails[0].specificationAndModel,
            inventoryQuantity: materialDetails[0].quantityIssued,
            unitName: materialDetails[0].unitOfMeasure,
            inboundBatchNumber: materialDetails[0].batchCode,
        };

        ElMessageBox.confirm(`确认要执行出库吗？物料信息: ${JSON.stringify(materialDetails)}`, '确认出库', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(async () => {
            try {
                await updatWmIssueLine(sa);
                ElMessage.success('出库成功！');
                 // 更新领料单的状态为已完成
                 await updatproductionPickingzt({ id: pickingId, status: 1 }); // 假设 updatePicking 是更新状态的接口
                await loadData(); // 刷新数据
            } catch (error) {
                ElMessage.error('出库失败：' + error.message);
            }
        }).catch(() => {
            ElMessage.info('已取消出库');
        });

    } catch (error) {
        ElMessage.error('获取物料信息失败：' + error.message);
    }
};

// 初始化状态（设置默认值）
const params2 = ref({
    currentPage: 1,
    pageSize: 5,
    productName: '',
    materialProductCode: '',
    materialProductName: '',
    inboundBatchNumber: '',
    warehouseName: '',
    supplierCode: '',
    supplierName: '',
    validityPeriodOfInventory: '',
});

const salesorder = ref([]);
const deleteDisabled = ref(true);
const isEditing = ref(true); // 控制产品列信息的显示与隐藏

const addMaterialDialogVisible = ref(false);
const addMaterialForm = reactive({
    materialProductCode: '',
    materialProductName: '',
    quantityIssued: 0,
    specificationAndModel: '',
    unitOfMeasure: '',
    inboundBatchNumber: '',
    warehouseName: '',
    warehouseAreaName: '',
    warehouseLocationName: '',
    remark: ''
});

// 打开新增物料对话框
const openAddMaterialDialog = () => {
    addMaterialDialogVisible.value = true;
    resetAddMaterialForm();
};

// 关闭新增物料对话框
const closeAddMaterialDialog = () => {
    addMaterialDialogVisible.value = false;
};

// 新增物料表单
const confirmAddMaterial = () => {
     
    const newMaterial = {
        materialProductCode: addMaterialForm.materialProductCode,
        productName: addMaterialForm.materialProductName,
        specificationAndModel: addMaterialForm.specificationAndModel,
        quantityIssued: addMaterialForm.quantityIssued,
        unitOfMeasure: addMaterialForm.unitOfMeasure,
        inboundBatchNumber: addMaterialForm.inboundBatchNumber,
        warehouseName: addMaterialForm.warehouseName,
        warehouseAreaName: addMaterialForm.warehouseAreaName,
        warehouseLocationName: addMaterialForm.warehouseLocationName,
        remark: addMaterialForm.remark,
    };
// 新增物料信息
insertWmIssueLine(newMaterial).then(res => {
    console.log(newMaterial);
    if(res=="成功"){
         ElMessage.success('新增物料成功');
        closeAddMaterialDialog();
        loadData(); // 刷新数据
    }else{
        ElMessage.error('新增物料失败：' + res);
    }
}).catch(error => {
    ElMessage.error('新增物料失败：' + error.message);
});


    // 关闭对话框
    addMaterialDialogVisible.value = false;
    // 重置新增表单
    resetAddMaterialForm();
};

const resetAddMaterialForm = () => {
    addMaterialForm.materialProductCode = '';
    addMaterialForm.materialProductName = '';
    addMaterialForm.quantityIssued = 0;
    addMaterialForm.specificationAndModel = '';
    addMaterialForm.unitOfMeasure = '';
    addMaterialForm.inboundBatchNumber = '';
    addMaterialForm.warehouseName = '';
    addMaterialForm.warehouseAreaName = '';
    addMaterialForm.warehouseLocationName = '';
    addMaterialForm.remark = '';
};

const selectedRows = ref([]); // 用于存储选中的行
// 在确保数据已加载之后再赋值

const handleSelectionChange2 = (val) => {
    selectedRows.value = val; // 更新为选中的行
};

const WarehouSeonhand = ref(false);
const wuliaoselect = async () => {
    try {
        WarehouSeonhand.value = true; // 打开对话框
        const pageResult2 = await findStock(params2.value);
        salesorder.value = pageResult2.records;
    } catch (error) {
        ElMessage({ type: 'error', message: '加载物料失败：' + error.message });
    }
};
// 错误示例


const confirmWUliao = async () => {
    if (!selectedRows.value.length) {
        ElMessage.warning('请先选择物料');
        return;
    }

    const selectedRow = selectedRows.value[0];

    addMaterialForm.materialProductCode = selectedRow.materialProductCode;
    addMaterialForm.materialProductName = selectedRow.materialProductName;
    addMaterialForm.quantityIssued = selectedRow.inventoryQuantity;
    addMaterialForm.specificationAndModel = selectedRow.specificationAndModel;
    addMaterialForm.unitOfMeasure = selectedRow.unitName;
    addMaterialForm.inboundBatchNumber = selectedRow.inboundBatchNumber;
    addMaterialForm.warehouseName = selectedRow.warehouseName;
    addMaterialForm.warehouseAreaName = selectedRow.warehouseAreaName;
    addMaterialForm.warehouseLocationName = selectedRow.warehouseLocationName;
    addMaterialForm.remark = selectedRow.remark;

    nextTick(() => {
        WarehouSeonhand.value = false; // 关闭对话框
        addMaterialDialogVisible.value = true; // 打开新增物料对话框
    });
};

// 搜索参数
const params = ref({
    currentPage: 1,
    pageSize: 10,
    pickingId: '',
    pickingName: '',
    pickingDate: '',
    status: ''
});

// 分页大小
const pageSizes = [2, 5, 10, 20];

// 页面加载时获取数据
onMounted(async () => {
    await loadData();
});

// 获取数据函数
const loadData = async () => {
    pageResult.value = await findproductionPicking(params.value);
    tableData.value = pageResult.value.records;
};

// 处理搜索
const handleSearch = async () => {
    await loadData();
};

// 重置搜索参数
const handleReset = async () => {
    Object.assign(params.value, {
        currentPage: 1,
        pageSize: 10,
        pickingId: '',
        pickingName: '',
        pickingDate: '',
        status: ''
    });
    await loadData();
};

// 分页大小变化
const handleSizeChange = async (size) => {
    params.value.pageSize = size;
    await loadData();
};

// 当前页变化
const handleCurrentChange = async (currentPage) => {
    params.value.currentPage = currentPage;
    await loadData();
};

// 选中行变化
const handleSelectionChange = (val) => {
    deleteDisabled.value = !val.length;
};

// 删除选中行
const handleDelete = () => {
    if (!selectedRows.value.length) {
        ElMessage.warning('请先选择要删除的项');
        return;
    }

    ElMessageBox.confirm('是否确认删除这些数据项？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deleteSelectedRows();
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};

const deleteSelectedRows = async () => {
    const selectedIds = selectedRows.value.map(row => row.id);
    try {
        await deletePicking(selectedIds);
        ElMessage({ type: 'success', message: '删除成功' });
        await loadData();
    } catch (error) {
        ElMessage({ type: 'error', message: '删除失败：' + error.message });
    }
};

// 确认新增
const confirmAdd = async () => {
    try {
        console.log('提交的数据:', form);
        await insertPicking(form);

        // dialogFormVisible.value = false;
        await loadData();
    } catch (error) {
        ElMessage.error('新增失败：' + error.message);
    }
};
const isNew = ref(true); // 新增状态标志
const form = reactive({
    id:'',
    pickingId: '',
    pickingName: '',
    pickingDate: '',
    status: '0', // 将状态默认为草稿
    remark: '',
    productionCode: '',
    warehouseNames: [], // 仓库
    // materialResult:[] //子表数据
});

// 在 openInsert 方法中
const openInsert = async () => {
    dialogFormVisible.value = true;
    title.value = '新增设备类型';
    isNew.value = true;
    isEditing.value = false; // 新增时隐藏物料信息
    options.value = await findWarehousesList(); // 获取仓库列表

    // 确保 form.warehouseNames 是一个数组并且有三个元素（仓库ID、库区ID、库位ID）
    if (Array.isArray(form.warehouseNames) && form.warehouseNames.length === 3) {
        const [warehouseId, areaId, locationCode] = form.warehouseNames;

        // 查找仓库信息
        const warehouse = options.value.find(item => item.value === warehouseId);
        if (warehouse) {
            form.warehouseId = warehouseId + '';
            form.warehouseName = warehouse.label;

            // 查找库区信息
            const area = warehouse.children.find(it => it.value === areaId);
            if (area) {
                form.areaName = area.label + "";
                form.areaId = areaId;

                // 查找库位信息
                const location = area.children.find(i => i.value === locationCode);
                if (location) {
                    form.locationCode = locationCode + "";
                    form.locationName = location.label;
                }
            }
        }

        console.log("仓库信息设置完成:", form);
    } else {
        console.warn("无效的仓库名称数组:", form.warehouseNames);
    }

    resetForm();
    form.status = '0'; // 设置状态为草稿
    resetMaterialInfo();
};

// 重置物料信息
const resetMaterialInfo = () => {
    materialResult.value = []; // 清空物料信息表格的数据
    selectedRowsWuliao.value = []; // 清空选中的物料
};

const materialResult = ref([]);

const openUpdate = async (row) => {
    try {
        dialogFormVisible.value = true;
        title.value = '修改设备类型';
        isEditing.value = true;
        isNew.value = false; // 修改状态

        // 获取仓库列表
        options.value = await findWarehousesList();

        // 确保在重置表单之前保存原始数据
        const originalData = { ...row };

        resetForm(); // 重置表单

        // 手动赋值，确保每一项都赋值给 form
        Object.keys(originalData).forEach(key => {
            if (key in form) {
                form[key] = originalData[key] || ''; // 确保赋值并提供默认值
            }
        });

        
        const params = { id: row.id };
        if (!params.id) {
            ElMessage.error('领料单ID无效');
            return;
        }

        // 读取物料信息
        try {
            const res = await findWmIssueLine(params); // 调用接口获取物料信息
            materialResult.value = res; // 将物料信息存入 materialResult
        } catch (error) {
            ElMessage.error('获取物料信息失败：' + error.message);
        }

        console.log(materialResult.value);
        console.log(form);

    } catch (error) {
        ElMessage.error('打开修改对话框时出错：' + error.message);
    }
};

// 重置表单数据
const resetForm = () => {
    form.pickingId = '';
    form.pickingName = '';
    form.productionCode = '';
    form.warehouseCode = ''; // 确保添加了仓库编码
    form.status = '';
    form.remark = '';
    form.warehouseNames = [];
    form.codeChangeNumber='';
    resetAddMaterialForm();
};


// 确认更新
const confirmUpdate = async () => {
   
        // form.list = xiaoshoudindanTable.value.getSelectionRows()
        // console.log(form);
        // const updatedMaterial = {
        //     materialProductCode: addMaterialForm.materialProductCode,
        //     productName: addMaterialForm.materialProductName,
        //     specificationAndModel: addMaterialForm.specificationAndModel,
        //     quantityIssued: addMaterialForm.quantityIssued,
        //     unitOfMeasure: addMaterialForm.unitOfMeasure,
        //     inboundBatchNumber: addMaterialForm.inboundBatchNumber,
        //     warehouseName: addMaterialForm.warehouseName,
        //     warehouseAreaName: addMaterialForm.warehouseAreaName,
        //     warehouseLocationName: addMaterialForm.warehouseLocationName,
        //     remark: addMaterialForm.remark,
        // };
        form.materialResult = materialResult.value; // 更新物料信息
        await updatePicking(form).then(async res => {
        if(res == "成功"){
            ElMessage.success('修改成功');
            await loadData();
            dialogFormVisible.value = false; // 关闭对话框
        }else{
            ElMessage.error('修改失败');
        }
     
    }); 
};

// 关闭对话框
const closeDialog = () => {
    dialogFormVisible.value = false;
    WarehouSeonhand.value = false; // 关闭对话框
    resetForm();
};

// 清空所有选择
const clearAll = () => {
    selectedRows.value = []; // 清空选中的行
    ElMessage.success('已清空所有选择'); // 提示用户
};

// 控制搜索框的显示与隐藏
const toggleSearchVisibility = () => {
    const searchForm = document.querySelector('.login-log-container > .el-form');
    if (searchForm) {
        searchForm.style.display = searchForm.style.display === 'none' ? 'block' : 'none';
    }
};
</script>

<style scoped>
.button-right {
    text-align: right;
}

.button-group {
    margin-top: 20px;
    margin-bottom: 10px;
}

.demo-pagination-block .el-pagination {
    justify-content: end;
    margin-top: 20px;
}
</style>
